#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*-
from flask import Flask, render_template ,flash, redirect, url_for, send_file, request, Response
import serial #导入模块
import re
import _thread
import time
#import cv2
import os,json

# gevent-websocket
from geventwebsocket.handler import WebSocketHandler
# 承载服务
from geventwebsocket.server import WSGIServer
# 语法提示
from geventwebsocket.websocket import WebSocket

class_name = "./pic/"

def gstreamer_pipeline(
        capture_width=1280,
        capture_height=720,
        display_width=1280,
        display_height=720,
        framerate=60,
        flip_method=0,
):
    return (
            "nvarguscamerasrc ! "
            "video/x-raw(memory:NVMM), "
            "width=(int)%d, height=(int)%d, "
            "format=(string)NV12, framerate=(fraction)%d/1 ! "
            "nvvidconv flip-method=%d ! "
            "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
            "videoconvert ! "
            "video/x-raw, format=(string)BGR ! appsink"
            % (
                capture_width,
                capture_height,
                framerate,
                flip_method,
                display_width,
                display_height,
            )
    )


def show_camera():
    cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=0), cv2.CAP_GSTREAMER)
    index = "now"
    if cap.isOpened():
        flag, img = cap.read()
        #cv2.imshow("CSI Camera", img)
        
        cv2.imwrite("%s/%s.jpg" % (class_name, index), cv2.resize(img, (1280, 720), interpolation=cv2.INTER_AREA))
        print("%s: %s 张图片" % (class_name, index))
        #index += 1
        #kk = cv2.waitKey(1)
        # do other things
        #if kk == ord('q'):  # 按下 q 键，退出
    else:
        print("Open Camera failed")

    cap.release()

def laser_init(portx):
    try:
        #端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
        #portx="/dev/ttyUSB0"
        #波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
        bps=19200
        #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
        timex=0.5
        # 打开串口，并得到串口对象
        ser=serial.Serial(portx,bps,timeout=timex)

        # 写数据
        result=ser.write("O".encode("gbk"))

        sensor_respond=ser.readlines()
        sensor_rec=''.join('%s' %id for id in sensor_respond)
        #print(sensor_rec)
        
        if (sensor_rec.find("OK")!=-1):
            print("激光传感器打开成功")
            return True
        else:
            print("激光传感器打开失败")
            return False
            
        print("激光传感器回复:",sensor_respond)

        ser.close()#关闭串口
    except Exception as e:
        print("---激光传感器串口初始化异常---：",e)
        return False

        

def laser_read(portx):
    bps=19200
        #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
    timex=0.5
        # 打开串口，并得到串口对象
    ser=serial.Serial(portx,bps,timeout=timex)

    # 写数据
    result=ser.write("D".encode("gbk"))
    
    sensor_respond=ser.readlines()
    sensor_rec=''.join('%s' %id for id in sensor_respond)
    
    if (sensor_rec.find("Er")!=-1):
        print("激光传感器测量错误")
        return str(0)
        
    list1 = sensor_rec.split(',')
    print("激光传感器回复:",list1)
    sensor_rec2=''.join('%s' %id for id in list1[0])
    
    #判断收到的数据里面是否包含数字
    if(bool(re.search(r'\d', sensor_rec2))):
        find_float = lambda x: re.search("\d+(\.\d+)?",x).group()
        laser_value=find_float(sensor_rec2)
    
    else:
        print("激光传感器测量错误")
        return str(0)
        
    ser.close()#关闭串口
    print("激光传感器测得的距离为：",laser_value)
    
    if(laser_value==""):
        return str(0)
    
    #print(laser_value)
    return laser_value
    
picDir = "./a.png"
distanceLaser = -1 #M
sensor_init_flag = False 
battery = 95
agvStatus = '0'
'''
agvStatus can be "0 1 2 3 4"
'''
def answerDate():
    ''' respon json data'''
    data = {"battery":battery,"status":agvStatus,"measure":distanceLaser}
    answer = {"erron":0,"data":data}
    return answer
def agv_read(portx):
    bps=19200
        #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
    timex=0.5
        # 打开串口，并得到串口对象
    ser=serial.Serial(portx,bps,timeout=timex)
    ##read agvStatus
    #sensor_respond=ser.readlines()
    return -1
    
def agv_set(portx,cmd='0'):
    bps=19200
        #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
    timex=0.5
        # 打开串口，并得到串口对象
    #ser=serial.Serial(portx,bps,timeout=timex)
    # 写数据
    date = [0x3a,0x43,0x4d,0x44,0x3d]+[cmd]+['\r','\n']
    #result=ser.write(date)
    print (date)

app = Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
    answer = answerDate()
    return Response(json.dumps(answer),content_type='application/json')


@app.route('/agv/measure')
def measure():
    global distanceLaser
    if(sensor_init_flag == True):
        pass
        #distanceLaser=laser_read("/dev/ttyUSB0")

    distanceLaser = 100 # for test!
    answer = answerDate()
    distanceLaser = -1
    return Response(json.dumps(answer),content_type='application/json')


@app.route('/cameraShot')
def cameraShot():
    #show_camera()
    return send_file(picDir, mimetype='image/jpeg')
    
@app.route('/agv/ctrl')
def agvCtrl():
    arg=request.args.get('arg')
    cmd=request.args.get('cmd')
    #
    global agvStatus
    
    answer = {"erron":0,"cmd":cmd,"arg":arg}
    if cmd =='0':
        agv_set("/dev/ttyUSB0",cmd)
        agvStatus = cmd
        pass
    elif cmd =='1':
        pass
    elif cmd =='2':
        pass
    elif cmd =='3':
        pass
    elif cmd =='4':
        pass
    return Response(json.dumps(answer),content_type='application/json')

armStatus = "0"
@app.route('/arm/ctrl')
def armCtrl():
    arg=request.args.get('arg')
    cmd=request.args.get('cmd')
    #
    global armStatus
    
    answer = {"erron":0,"cmd":cmd,"arg":arg}
    if cmd =='0':
        arm_set("/dev/ttyUSB2",cmd)
        armStatus = cmd
        pass
    elif cmd =='1':
        arm_set("/dev/ttyUSB2",cmd)
        armStatus = cmd
    elif cmd =='2':
        arm_set("/dev/ttyUSB2",cmd)
        armStatus = cmd
    elif cmd =='3':
        arm_set("/dev/ttyUSB2",cmd)
        armStatus = cmd

    return Response(json.dumps(answer),content_type='application/json')
        
if __name__=='__main__':
    sensor_init_flag = laser_init("/dev/ttyUSB0")
    app.run(debug=False,host='0.0.0.0')

#sensor_init_flag = laser_init("/dev/ttyUSB0")

#while(1):
#    if(sensor_init_flag):
#        distance1=laser_read("/dev/ttyUSB0")
  
